var choosesugindex=-1;
function search(){
    var inputbox=document.getElementById("inputbox");
    var searchText="https://www.baidu.com/s?ie=UTF-8&wd="+inputbox.value;
    // window.open();
    window.location.href=searchText;

}
function btnenter(){
    var key = event.keyCode;
    if(key==13){ //回车
        search();
    }else if(key==38 || key==40){ //up down
        console.log(choosesugindex);
        if(key==38){
            choosesugindex--;
        }
        if(key==40){
            choosesugindex++;
        }
        var list = document.getElementById("suggestlist").getElementsByTagName("li");
        if(choosesugindex<=-1){
            choosesugindex=list.length-1;
        }
        if(choosesugindex>=list.length){
            choosesugindex=0;
        }
        var opt = document.getElementById("inputbox");
        opt.value=list[choosesugindex].innerHTML;
        for(var i=0;i<list.length;i++){
            console.log("aa");
            list[i].style.backgroundColor="";
        }
        list[choosesugindex].style.backgroundColor="rgba(125,125,125,0.1)";

    }else{
        showsuggest();
    }
    
}
function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false 为同步请求
    xmlHttp.send( null );
    return xmlHttp.responseText;
}
function showsuggest() {
    choosesugindex=-1;

    //组装查询地址
    var sugurl = "http://suggestion.baidu.com/su?wd=#content#&cb=window.baidu.sug";
    var ul = document.getElementById("suggestlist");
    var content = document.getElementById("inputbox").value;
    if(content==""){
        ul.innerHTML="";
        document.getElementById("inputlist").style.borderRadius="8px 0 0 8px";
    }else{
        sugurl = sugurl.replace("#content#", content);

        //定义回调函数
        window.baidu = {
            sug: function(json) {
                var list = json.s;
                var inul = "";
                for(var i=0; i<list.length; i++){
                    inul+= "<li onclick=\"choosesug()\">"+list[i]+"</li>";
                }
                ul.innerHTML=inul;
                console.log(list);
                if(list.length!=0){
                    document.getElementById("inputlist").style.borderRadius="8px 0 8px 8px";
                }else{
                    document.getElementById("inputlist").style.borderRadius="8px 0 0 8px";
                }

            }
        }
    
        //动态添加JS脚本
        var script = document.createElement("script");
        script.src = sugurl;
        document.getElementsByTagName("head")[0].appendChild(script);
    
    }

}
function choosesug(){
    document.getElementById("inputbox").value=event.srcElement.innerHTML
    document.getElementById("suggestlist").innerHTML="";
    search();
}